// CinemaManagementSystem.java
package main.java.com.cinema.CinemaManagementSystem;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

// 导入所有需要的类 (修复包路径)
import main.java.com.cinema.model.User;
import main.java.com.cinema.model.Hall;
import main.java.com.cinema.model.Movie;
import main.java.com.cinema.model.Showtime;
import main.java.com.cinema.model.Ticket;
import main.java.com.cinema.model.SalesData;

import main.java.com.cinema.service.UserService;
import main.java.com.cinema.service.MovieService;
import main.java.com.cinema.service.ShowtimeService;
import main.java.com.cinema.service.TicketService;

import main.java.com.cinema.util.DataStorage;
import main.java.com.cinema.util.DatabaseUtil;

public class CinemaManagementSystem {
    private static Scanner scanner = new Scanner(System.in);
    private static UserService userService = new UserService();
    private static MovieService movieService = new MovieService();
    private static ShowtimeService showtimeService = new ShowtimeService();
    private static TicketService ticketService = new TicketService();
    private static User currentUser = null;

    // CinemaManagementSystem.java
    public static void main(String[] args) {
        // 初始化数据库
        System.out.println("初始化数据库...");
        DatabaseUtil.initializeDatabase();
        // 触发DataStorage静态初始化
        System.out.println("系统启动中...");
        int hallCount = DataStorage.halls.size(); // 这会触发静态初始化
        System.out.println("已加载 " + hallCount + " 个放映厅");

        while (true) {
            if (currentUser == null) {
                showMainMenu();
            } else {
                showUserMenu();
            }
        }
    }


    private static void showMainMenu() {
        System.out.println("\n======= 万东电影院管理系统 =======");
        System.out.println("1. 登录");
        System.out.println("0. 退出系统");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                login();
                break;
            case 0:
                System.out.println("感谢使用万东电影院管理系统！");
                System.exit(0);
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    private static void login() {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        User user = userService.login(username, password);
        if (user != null) {
            currentUser = user;
            System.out.println("登录成功！欢迎 " + user.getUsername());

            // 如果是新用户（密码未修改），强制修改密码
            if (!user.isPasswordChanged() && !"admin".equals(user.getUsername())) {
                forceChangePassword();
            }
        } else {
            System.out.println("用户名或密码错误！");
        }
    }

    private static void forceChangePassword() {
        System.out.println("检测到您是首次登录，请修改默认密码！");
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();
        System.out.print("请再次输入新密码: ");
        String confirmNewPassword = scanner.nextLine();

        if (newPassword.equals(confirmNewPassword)) {
            currentUser.setPassword(newPassword);
            currentUser.setPasswordChanged(true);
            userService.changePassword(currentUser.getUserId(), "123456", newPassword);
            System.out.println("密码修改成功！");
        } else {
            System.out.println("两次输入的密码不一致，登录失败！");
            currentUser = null;
        }
    }

    private static void showUserMenu() {
        System.out.println("\n======= 欢迎 " + currentUser.getUsername() + " =======");
        System.out.println("当前角色: " + getUserRoleName(currentUser.getRole()));

        switch (currentUser.getRole()) {
            case ADMIN:
                showAdminMenu();
                break;
            case MANAGER:
                showManagerMenu();
                break;
            case STAFF:
                showStaffMenu();
                break;
        }
    }

    // 管理员菜单
    private static void showAdminMenu() {
        System.out.println("1. 密码管理");
        System.out.println("2. 用户管理");
        System.out.println("3. 退出登录");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                handlePasswordManagement();
                break;
            case 2:
                handleUserManagement();
                break;
            case 3:
                currentUser = null;
                System.out.println("已退出登录！");
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    // 经理菜单
    private static void showManagerMenu() {
        System.out.println("1. 密码管理");
        System.out.println("2. 影片管理");
        System.out.println("3. 排片管理");
        System.out.println("4. 查看销售数据");
        System.out.println("5. 退出登录");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                handleManagerPasswordManagement();
                break;
            case 2:
                handleMovieManagement();
                break;
            case 3:
                handleShowtimeManagement();
                break;
            case 4:
                handleSalesDataView();
                break;
            case 5:
                currentUser = null;
                System.out.println("已退出登录！");
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    // 前台菜单
    private static void showStaffMenu() {
        System.out.println("1. 查看影片信息");
        System.out.println("2. 查看场次信息");
        System.out.println("3. 售票");
        System.out.println("4. 退票");
        System.out.println("5. 退出登录");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                listAllMovies();
                break;
            case 2:
                listShowtimes();
                break;
            case 3:
                sellTicket();
                break;
            case 4:
                refundTicket();
                break;
            case 5:
                currentUser = null;
                System.out.println("已退出登录！");
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    // 管理员密码管理
    private static void handlePasswordManagement() {
        System.out.println("\n======= 密码管理 =======");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置非管理员用户密码");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                changeOwnPassword();
                break;
            case 2:
                resetUserPassword();
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    // 经理密码管理
    private static void handleManagerPasswordManagement() {
        System.out.println("\n======= 密码管理 =======");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置前台用户密码");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                changeOwnPassword();
                break;
            case 2:
                resetStaffPassword();
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    private static void changeOwnPassword() {
        System.out.print("请输入原密码: ");
        String oldPassword = scanner.nextLine();
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();
        System.out.print("请再次输入新密码: ");
        String confirmNewPassword = scanner.nextLine();

        if (!newPassword.equals(confirmNewPassword)) {
            System.out.println("两次输入的新密码不一致！");
            return;
        }

        if (userService.changePassword(currentUser.getUserId(), oldPassword, newPassword)) {
            currentUser.setPassword(newPassword);
            System.out.println("密码修改成功！");
        } else {
            System.out.println("原密码错误，密码修改失败！");
        }
    }

    private static void resetUserPassword() {
        System.out.print("请输入要重置密码的用户名: ");
        String username = scanner.nextLine();
        User targetUser = userService.findUserByUsername(username);

        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (targetUser.getRole() == User.Role.ADMIN) {
            System.out.println("不能重置管理员密码！");
            return;
        }

        if (userService.resetPassword(currentUser.getUserId(), targetUser.getUserId())) {
            System.out.println("用户 " + username + " 的密码已重置为 123456");
        } else {
            System.out.println("密码重置失败！");
        }
    }

    private static void resetStaffPassword() {
        System.out.print("请输入要重置密码的前台用户名: ");
        String username = scanner.nextLine();
        User targetUser = userService.findUserByUsername(username);

        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        if (targetUser.getRole() != User.Role.STAFF) {
            System.out.println("只能重置前台用户的密码！");
            return;
        }

        if (userService.resetPassword(currentUser.getUserId(), targetUser.getUserId())) {
            System.out.println("前台用户 " + username + " 的密码已重置为 123456");
        } else {
            System.out.println("密码重置失败！");
        }
    }

    // 用户管理
    private static void handleUserManagement() {
        System.out.println("\n======= 用户管理 =======");
        System.out.println("1. 列出所有用户");
        System.out.println("2. 查询用户信息");
        System.out.println("3. 增加用户");
        System.out.println("4. 修改用户信息");
        System.out.println("5. 删除用户");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                listAllUsers();
                break;
            case 2:
                queryUser();
                break;
            case 3:
                addUser();
                break;
            case 4:
                updateUser();
                break;
            case 5:
                deleteUser();
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    private static void listAllUsers() {
        List<User> users = userService.listAllUsers();
        System.out.println("\n======= 所有用户信息 =======");
        System.out.printf("%-10s %-15s %-15s %-20s %-15s%n",
                "用户ID", "用户名", "角色", "手机号", "注册时间");
        System.out.println("------------------------------------------------------------");

        for (User user : users) {
            System.out.printf("%-10s %-15s %-15s %-20s %-15s%n",
                    user.getUserId(),
                    user.getUsername(),
                    getUserRoleName(user.getRole()),
                    user.getPhoneNumber() != null ? user.getPhoneNumber() : "无",
                    user.getRegistrationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    }

    private static void queryUser() {
        System.out.println("\n======= 查询用户 =======");
        System.out.println("1. 按用户ID查询");
        System.out.println("2. 按用户名查询");
        System.out.print("请选择查询方式: ");

        int choice = getIntInput();
        User user = null;

        switch (choice) {
            case 1:
                System.out.print("请输入用户ID: ");
                String userId = scanner.nextLine();
                user = userService.findUserById(userId);
                break;
            case 2:
                System.out.print("请输入用户名: ");
                String username = scanner.nextLine();
                user = userService.findUserByUsername(username);
                break;
            default:
                System.out.println("无效选项！");
                return;
        }

        if (user != null) {
            System.out.println("\n用户信息:");
            System.out.println("用户ID: " + user.getUserId());
            System.out.println("用户名: " + user.getUsername());
            System.out.println("角色: " + getUserRoleName(user.getRole()));
            System.out.println("手机号: " + (user.getPhoneNumber() != null ? user.getPhoneNumber() : "无"));
            System.out.println("注册时间: " + user.getRegistrationTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        } else {
            System.out.println("未找到用户！");
        }
    }

    private static void addUser() {
        System.out.println("\n======= 添加用户 =======");
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.println("请选择用户角色:");
        System.out.println("1. 经理");
        System.out.println("2. 前台");
        System.out.print("请选择: ");

        int roleChoice = getIntInput();
        User.Role role;
        switch (roleChoice) {
            case 1:
                role = User.Role.MANAGER;
                break;
            case 2:
                role = User.Role.STAFF;
                break;
            default:
                System.out.println("无效选项！");
                return;
        }

        System.out.print("请输入手机号: ");
        String phoneNumber = scanner.nextLine();

        if (userService.addUser(currentUser, username, password, role, phoneNumber)) {
            System.out.println("用户添加成功！");
        } else {
            System.out.println("用户添加失败！可能用户名或手机号已存在。");
        }
    }

    private static void updateUser() {
        System.out.println("\n======= 修改用户信息 =======");
        System.out.print("请输入要修改的用户ID: ");
        String userId = scanner.nextLine();

        User user = userService.findUserById(userId);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        if ("admin".equals(user.getUsername())) {
            System.out.println("不能修改admin账户！");
            return;
        }

        if (user.getRole() != User.Role.STAFF && user.getRole() != User.Role.MANAGER) {
            System.out.println("只能修改经理或前台用户的信息！");
            return;
        }

        System.out.println("当前用户信息:");
        System.out.println("用户名: " + user.getUsername());
        System.out.println("角色: " + getUserRoleName(user.getRole()));
        System.out.println("手机号: " + (user.getPhoneNumber() != null ? user.getPhoneNumber() : "无"));

        System.out.println("\n请选择要修改的信息:");
        System.out.println("1. 修改角色");
        System.out.println("2. 修改手机号");
        System.out.print("请选择: ");

        int choice = getIntInput();
        User.Role newRole = user.getRole();
        String newPhoneNumber = user.getPhoneNumber();

        switch (choice) {
            case 1:
                System.out.println("请选择新角色:");
                System.out.println("1. 经理");
                System.out.println("2. 前台");
                System.out.print("请选择: ");
                int roleChoice = getIntInput();
                switch (roleChoice) {
                    case 1:
                        newRole = User.Role.MANAGER;
                        break;
                    case 2:
                        newRole = User.Role.STAFF;
                        break;
                    default:
                        System.out.println("无效选项！");
                        return;
                }
                break;
            case 2:
                System.out.print("请输入新手机号: ");
                newPhoneNumber = scanner.nextLine();
                break;
            default:
                System.out.println("无效选项！");
                return;
        }

        if (userService.updateUser(currentUser, userId, newRole, newPhoneNumber)) {
            System.out.println("用户信息修改成功！");
        } else {
            System.out.println("用户信息修改失败！手机号可能已存在。");
        }
    }

    private static void deleteUser() {
        System.out.println("\n======= 删除用户 =======");
        System.out.print("请输入要删除的用户ID: ");
        String userId = scanner.nextLine();

        User user = userService.findUserById(userId);
        if (user == null) {
            System.out.println("用户不存在！");
            return;
        }

        if ("admin".equals(user.getUsername())) {
            System.out.println("不能删除admin账户！");
            return;
        }

        System.out.println("警告：删除操作不可恢复！");
        System.out.print("确认删除用户 " + user.getUsername() + " 吗？(y/N): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            if (userService.deleteUser(currentUser, userId)) {
                System.out.println("用户删除成功！");
            } else {
                System.out.println("用户删除失败！");
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    // 影片管理
    private static void handleMovieManagement() {
        System.out.println("\n======= 影片管理 =======");
        System.out.println("1. 列出所有影片");
        System.out.println("2. 添加影片");
        System.out.println("3. 修改影片");
        System.out.println("4. 删除影片");
        System.out.println("5. 查询影片");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                listAllMovies();
                break;
            case 2:
                addMovie();
                break;
            case 3:
                updateMovie();
                break;
            case 4:
                deleteMovie();
                break;
            case 5:
                searchMovies();
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    private static void listAllMovies() {
        List<Movie> movies = movieService.listAllMovies();
        System.out.println("\n======= 所有影片信息 =======");
        System.out.printf("%-10s %-20s %-15s %-10s %-6s%n",
                "影片ID", "片名", "导演", "时长(分钟)", "评分");
        System.out.println("------------------------------------------------------------------");

        for (Movie movie : movies) {
            System.out.printf("%-10s %-20s %-15s %-10d %-6.1f%n",
                    movie.getId(),
                    movie.getTitle(),
                    movie.getDirector(),
                    movie.getDuration(),
                    movie.getRating());
        }
    }

    private static void addMovie() {
        System.out.println("\n======= 添加影片 =======");
        System.out.print("请输入片名: ");
        String title = scanner.nextLine();
        System.out.print("请输入导演: ");
        String director = scanner.nextLine();
        System.out.print("请输入主演(多个主演用逗号分隔): ");
        String actorsStr = scanner.nextLine();
        String[] actors = actorsStr.split(",");
        System.out.print("请输入剧情简介: ");
        String synopsis = scanner.nextLine();
        System.out.print("请输入时长(分钟): ");
        int duration = getIntInput();
        System.out.print("请输入评分(0-10): ");
        double rating = getDoubleInput();

        if (movieService.addMovie(currentUser.getUsername(), title, director, actors, synopsis, duration, rating)) {
            System.out.println("影片添加成功！");
        } else {
            System.out.println("影片添加失败！");
        }
    }

    private static void updateMovie() {
        System.out.println("\n======= 修改影片 =======");
        System.out.print("请输入要修改的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = movieService.findMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("当前影片信息:");
        System.out.println("片名: " + movie.getTitle());
        System.out.println("导演: " + movie.getDirector());
        System.out.print("请输入新片名(回车保持不变): ");
        String title = scanner.nextLine();
        if (title.isEmpty()) title = movie.getTitle();

        System.out.print("请输入新导演(回车保持不变): ");
        String director = scanner.nextLine();
        if (director.isEmpty()) director = movie.getDirector();

        System.out.print("请输入主演(多个主演用逗号分隔，回车保持不变): ");
        String actorsStr = scanner.nextLine();
        String[] actors = movie.getActors();
        if (!actorsStr.isEmpty()) {
            actors = actorsStr.split(",");
        }

        System.out.print("请输入剧情简介(回车保持不变): ");
        String synopsis = scanner.nextLine();
        if (synopsis.isEmpty()) synopsis = movie.getSynopsis();

        System.out.print("请输入时长(分钟，0表示保持不变): ");
        int duration = getIntInput();
        if (duration <= 0) duration = movie.getDuration();

        System.out.print("请输入评分(0-10，-1表示保持不变): ");
        double rating = getDoubleInput();
        if (rating < 0) rating = movie.getRating();

        if (movieService.updateMovie(currentUser.getUsername(), movieId, title, director, actors, synopsis, duration, rating)) {
            System.out.println("影片修改成功！");
        } else {
            System.out.println("影片修改失败！");
        }
    }

    private static void deleteMovie() {
        System.out.println("\n======= 删除影片 =======");
        System.out.print("请输入要删除的影片ID: ");
        String movieId = scanner.nextLine();

        Movie movie = movieService.findMovieById(movieId);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.println("影片信息:");
        System.out.println("片名: " + movie.getTitle());
        System.out.println("导演: " + movie.getDirector());

        System.out.println("警告：删除操作不可恢复！");
        System.out.print("确认删除影片 " + movie.getTitle() + " 吗？(y/N): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            if (movieService.deleteMovie(currentUser.getUsername(), movieId)) {
                System.out.println("影片删除成功！");
            } else {
                System.out.println("影片删除失败！");
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    private static void searchMovies() {
        System.out.println("\n======= 查询影片 =======");
        System.out.print("请输入片名(可选): ");
        String title = scanner.nextLine();
        System.out.print("请输入导演(可选): ");
        String director = scanner.nextLine();
        System.out.print("请输入主演(可选): ");
        String actor = scanner.nextLine();

        List<Movie> movies = movieService.searchMovies(
                title.isEmpty() ? null : title,
                director.isEmpty() ? null : director,
                actor.isEmpty() ? null : actor
        );

        System.out.println("\n查询结果:");
        System.out.printf("%-10s %-20s %-15s %-10s %-6s%n",
                "影片ID", "片名", "导演", "时长(分钟)", "评分");
        System.out.println("------------------------------------------------------------------");

        for (Movie movie : movies) {
            System.out.printf("%-10s %-20s %-15s %-10d %-6.1f%n",
                    movie.getId(),
                    movie.getTitle(),
                    movie.getDirector(),
                    movie.getDuration(),
                    movie.getRating());
        }
    }

    // 排片管理
    private static void handleShowtimeManagement() {
        System.out.println("\n======= 排片管理 =======");
        System.out.println("1. 增加场次");
        System.out.println("2. 修改场次");
        System.out.println("3. 删除场次");
        System.out.println("4. 列出所有场次");
        System.out.print("请选择操作: ");

        int choice = getIntInput();
        switch (choice) {
            case 1:
                addShowtime();
                break;
            case 2:
                updateShowtime();
                break;
            case 3:
                deleteShowtime();
                break;
            case 4:
                listShowtimes();
                break;
            default:
                System.out.println("无效选项，请重新选择！");
        }
    }

    private static void addShowtime() {
        System.out.println("\n======= 增加场次 =======");
        System.out.println("调试: 检查DataStorage中的放映厅数量: " + DataStorage.halls.size());

        // 显示所有影片
        List<Movie> movies = movieService.listAllMovies();
        if (movies.isEmpty()) {
            System.out.println("暂无影片，请先添加影片！");
            return;
        }

        System.out.println("可选影片:");
        for (int i = 0; i < movies.size(); i++) {
            Movie movie = movies.get(i);
            System.out.println((i+1) + ". " + movie.getTitle() + " (" + movie.getDuration() + "分钟)");
        }
        System.out.print("请选择影片(输入序号): ");
        int movieChoice = getIntInput();
        if (movieChoice < 1 || movieChoice > movies.size()) {
            System.out.println("无效选择！");
            return;
        }
        String movieId = movies.get(movieChoice-1).getId();

        // 显示所有放映厅
        System.out.println("\n可选放映厅:");
        List<Hall> halls = DataStorage.getAllHalls(); // 使用getAllHalls方法
        if (halls.isEmpty()) {
            System.out.println("暂无放映厅信息！");
            System.out.println("调试: DataStorage.halls是否为空: " + DataStorage.halls.isEmpty());
            return;
        }

        for (int i = 0; i < halls.size(); i++) {
            Hall hall = halls.get(i);
            System.out.println((i+1) + ". " + hall.getName() + " (" + hall.getRows() + "排×" + hall.getSeatsPerRow() + "座)");
        }
        System.out.print("请选择放映厅(输入序号): ");
        int hallChoice = getIntInput();
        if (hallChoice < 1 || hallChoice > DataStorage.halls.size()) {
            System.out.println("无效选择！");
            return;
        }
        String hallId = DataStorage.halls.get(hallChoice-1).getId();

        System.out.print("请输入放映时间(格式: yyyy-MM-dd HH:mm): ");
        String timeStr = scanner.nextLine();
        LocalDateTime startTime;
        try {
            startTime = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } catch (Exception e) {
            System.out.println("时间格式错误！");
            return;
        }

        System.out.print("请输入票价: ");
        double price = getDoubleInput();

        if (showtimeService.addShowtime(currentUser.getUsername(), movieId, hallId, startTime, price)) {
            System.out.println("场次添加成功！");
        } else {
            System.out.println("场次添加失败！");
        }
    }

    private static void updateShowtime() {
        System.out.println("\n======= 修改场次 =======");
        System.out.print("请输入要修改的场次ID: ");
        String showtimeId = scanner.nextLine();

        Showtime showtime = showtimeService.findShowtimeById(showtimeId);
        if (showtime == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 显示场次信息
        Movie movie = movieService.findMovieById(showtime.getMovieId());
        Hall hall = DataStorage.getHallById(showtime.getHallId());
        System.out.println("当前场次信息:");
        System.out.println("影片: " + (movie != null ? movie.getTitle() : "未知"));
        System.out.println("放映厅: " + (hall != null ? hall.getName() : "未知"));
        System.out.println("时间: " + showtime.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("票价: " + showtime.getPrice());

        System.out.println("\n请选择要修改的信息:");
        System.out.println("1. 修改影片");
        System.out.println("2. 修改时间");
        System.out.println("3. 修改票价");
        System.out.print("请选择: ");

        int choice = getIntInput();
        String newMovieId = null;
        LocalDateTime newStartTime = null;
        double newPrice = -1;

        switch (choice) {
            case 1:
                // 显示所有影片
                List<Movie> movies = movieService.listAllMovies();
                System.out.println("可选影片:");
                for (int i = 0; i < movies.size(); i++) {
                    Movie m = movies.get(i);
                    System.out.println((i+1) + ". " + m.getTitle());
                }
                System.out.print("请选择新影片(输入序号): ");
                int movieChoice = getIntInput();
                if (movieChoice < 1 || movieChoice > movies.size()) {
                    System.out.println("无效选择！");
                    return;
                }
                newMovieId = movies.get(movieChoice-1).getId();
                break;
            case 2:
                System.out.print("请输入新时间(格式: yyyy-MM-dd HH:mm): ");
                String timeStr = scanner.nextLine();
                try {
                    newStartTime = LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                } catch (Exception e) {
                    System.out.println("时间格式错误！");
                    return;
                }
                break;
            case 3:
                System.out.print("请输入新票价: ");
                newPrice = getDoubleInput();
                break;
            default:
                System.out.println("无效选项！");
                return;
        }

        if (showtimeService.updateShowtime(currentUser.getUsername(), showtimeId, newMovieId, newStartTime, newPrice)) {
            System.out.println("场次修改成功！");
        } else {
            System.out.println("场次修改失败！可能已有票售出。");
        }
    }

    private static void deleteShowtime() {
        System.out.println("\n======= 删除场次 =======");
        System.out.print("请输入要删除的场次ID: ");
        String showtimeId = scanner.nextLine();

        Showtime showtime = showtimeService.findShowtimeById(showtimeId);
        if (showtime == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 显示场次信息
        Movie movie = movieService.findMovieById(showtime.getMovieId());
        Hall hall = DataStorage.getHallById(showtime.getHallId());
        System.out.println("场次信息:");
        System.out.println("影片: " + (movie != null ? movie.getTitle() : "未知"));
        System.out.println("放映厅: " + (hall != null ? hall.getName() : "未知"));
        System.out.println("时间: " + showtime.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("票价: " + showtime.getPrice());

        System.out.println("警告：删除操作不可恢复！");
        System.out.print("确认删除该场次吗？(y/N): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            if (showtimeService.deleteShowtime(currentUser.getUsername(), showtimeId)) {
                System.out.println("场次删除成功！");
            } else {
                System.out.println("场次删除失败！可能已有票售出。");
            }
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    private static void listShowtimes() {
        System.out.println("\n======= 场次信息 =======");
        System.out.println("1. 显示最近一周");
        System.out.println("2. 显示当天");
        System.out.println("3. 显示最近3天");
        System.out.print("请选择: ");

        int choice = getIntInput();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = now;
        LocalDateTime end = now.plusDays(7);

        switch (choice) {
            case 1:
                // 默认最近一周
                break;
            case 2:
                start = now.withHour(0).withMinute(0).withSecond(0);
                end = now.withHour(23).withMinute(59).withSecond(59);
                break;
            case 3:
                end = now.plusDays(3);
                break;
            default:
                System.out.println("无效选项，显示默认最近一周！");
        }

        List<Showtime> showtimes = showtimeService.listShowtimesByDateRange(start, end);
        System.out.println("\n场次列表:");
        System.out.printf("%-10s %-20s %-15s %-20s %-10s %-10s %-10s%n",
                "场次ID", "影片", "放映厅", "时间", "票价", "总座位", "空闲座位");
        System.out.println("--------------------------------------------------------------------------------------------------------");

        for (Showtime showtime : showtimes) {
            Movie movie = movieService.findMovieById(showtime.getMovieId());
            Hall hall = DataStorage.getHallById(showtime.getHallId());
            System.out.printf("%-10s %-20s %-15s %-20s %-10.2f %-10d %-10d%n",
                    showtime.getId(),
                    movie != null ? movie.getTitle() : "未知",
                    hall != null ? hall.getName() : "未知",
                    showtime.getStartTime().format(DateTimeFormatter.ofPattern("MM-dd HH:mm")),
                    showtime.getPrice(),
                    showtime.getTotalSeats(),
                    showtime.getAvailableSeats());
        }
    }

    // 销售数据查看 (删除重复的方法，保留一个)
    private static void handleSalesDataView() {
        System.out.println("\n======= 销售数据 =======");
        System.out.println("1. 查看当日销售数据");
        System.out.println("2. 查看当周销售数据");
        System.out.println("3. 查看当月销售数据");
        System.out.print("请选择: ");

        int choice = getIntInput();
        LocalDateTime now = LocalDateTime.now();
        SalesData salesData = null;

        switch (choice) {
            case 1:
                salesData = ticketService.getDailySalesData(now);
                System.out.println("\n======= 当日销售数据 =======");
                break;
            case 2:
                salesData = ticketService.getWeeklySalesData(now);
                System.out.println("\n======= 当周销售数据 =======");
                break;
            case 3:
                salesData = ticketService.getMonthlySalesData(now);
                System.out.println("\n======= 当月销售数据 =======");
                break;
            default:
                System.out.println("无效选项！");
                return;
        }

        if (salesData != null) {
            System.out.println("售票数量: " + salesData.getTotalSoldTickets() + " 张");
            System.out.println("售票金额: " + String.format("%.2f", salesData.getTotalSalesAmount()) + " 元");
            System.out.println("退票数量: " + salesData.getTotalRefundedTickets() + " 张");
            System.out.println("退票金额: " + String.format("%.2f", salesData.getTotalRefundAmount()) + " 元");
            System.out.println("净收入: " + String.format("%.2f", salesData.getNetAmount()) + " 元");
        }
    }

    // 前台售票功能
    private static void sellTicket() {
        System.out.println("\n======= 售票 =======");
        listShowtimes();

        System.out.print("\n请输入场次ID: ");
        String showtimeId = scanner.nextLine();

        Showtime showtime = showtimeService.findShowtimeById(showtimeId);
        if (showtime == null) {
            System.out.println("场次不存在！");
            return;
        }

        // 显示座位信息
        displaySeatMap(showtime);

        System.out.print("请输入排数: ");
        int row = getIntInput();
        System.out.print("请输入座位号: ");
        int seat = getIntInput();

        // 检查座位有效性
        if (row < 1 || row > showtime.getSeatStatus().length ||
                seat < 1 || seat > showtime.getSeatStatus()[row-1].length) {
            System.out.println("座位号无效！");
            return;
        }

        // 检查座位是否已被占用
        if (showtime.isSeatOccupied(row-1, seat-1)) {
            System.out.println("该座位已被占用！");
            return;
        }

        if (ticketService.sellTicket(currentUser.getUsername(), showtimeId, row-1, seat-1)) {
            System.out.println("售票成功！");
            // 显示票务信息
            Ticket ticket = null;
            List<Ticket> tickets = ticketService.listAllTickets();
            for (Ticket t : tickets) {
                if (t.getShowtimeId().equals(showtimeId) &&
                        t.getRow() == row-1 &&
                        t.getSeat() == seat-1 &&
                        t.getUserId().equals(currentUser.getUsername())) {
                    ticket = t;
                    break;
                }
            }

            if (ticket != null) {
                Movie movie = movieService.findMovieById(showtime.getMovieId());
                Hall hall = DataStorage.getHallById(showtime.getHallId());
                System.out.println("\n======= 电影票信息 =======");
                System.out.println("电子票号: " + ticket.getId());
                System.out.println("影片: " + (movie != null ? movie.getTitle() : "未知"));
                System.out.println("时间: " + showtime.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
                System.out.println("放映厅: " + (hall != null ? hall.getName() : "未知"));
                System.out.println("座位: " + row + "排" + seat + "座");
                System.out.println("票价: " + String.format("%.2f", ticket.getPrice()) + " 元");
            }
        } else {
            System.out.println("售票失败！");
        }
    }

    // 显示座位图
    private static void displaySeatMap(Showtime showtime) {
        System.out.println("\n座位图 (O: 空闲, X: 已售):");
        boolean[][] seats = showtime.getSeatStatus();

        // 打印列号
        System.out.print("   ");
        for (int j = 0; j < seats[0].length; j++) {
            System.out.printf("%3d", j+1);
        }
        System.out.println();

        // 打印座位状态
        for (int i = 0; i < seats.length; i++) {
            System.out.printf("%2d ", i+1);
            for (int j = 0; j < seats[i].length; j++) {
                if (seats[i][j]) {
                    System.out.print("  X");
                } else {
                    System.out.print("  O");
                }
            }
            System.out.println();
        }
    }

    // 退票功能
    private static void refundTicket() {
        System.out.println("\n======= 退票 =======");
        System.out.print("请输入电子票号: ");
        String ticketId = scanner.nextLine();

        Ticket ticket = ticketService.findTicketById(ticketId);
        if (ticket == null) {
            System.out.println("票号不存在！");
            return;
        }

        if (ticket.isRefunded()) {
            System.out.println("该票已退！");
            return;
        }

        Showtime showtime = showtimeService.findShowtimeById(ticket.getShowtimeId());
        if (showtime == null) {
            System.out.println("场次信息不存在！");
            return;
        }

        Movie movie = movieService.findMovieById(showtime.getMovieId());
        Hall hall = DataStorage.getHallById(showtime.getHallId());

        System.out.println("票务信息:");
        System.out.println("影片: " + (movie != null ? movie.getTitle() : "未知"));
        System.out.println("时间: " + showtime.getStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        System.out.println("放映厅: " + (hall != null ? hall.getName() : "未知"));
        System.out.println("座位: " + (ticket.getRow()+1) + "排" + (ticket.getSeat()+1) + "座");
        System.out.println("票价: " + String.format("%.2f", ticket.getPrice()) + " 元");

        System.out.print("确认退票吗？(y/N): ");
        String confirm = scanner.nextLine();

        if ("y".equalsIgnoreCase(confirm) || "yes".equalsIgnoreCase(confirm)) {
            if (ticketService.refundTicket(currentUser.getUsername(), ticketId)) {
                System.out.println("退票成功！");

                // 计算退款金额（根据需求，提前一小时退票扣除10%手续费）
                LocalDateTime showtimeStart = showtime.getStartTime();
                LocalDateTime now = LocalDateTime.now();
                double refundAmount = ticket.getPrice();

                if (showtimeStart.isBefore(now.plusDays(1))) {
                    // 提前不到一天，扣除10%手续费
                    refundAmount *= 0.9;
                    System.out.println("退款金额: " + String.format("%.2f", refundAmount) + " 元 (扣除10%手续费)");
                } else {
                    System.out.println("退款金额: " + String.format("%.2f", refundAmount) + " 元");
                }
            } else {
                System.out.println("退票失败！可能已超过退票时间。");
            }
        } else {
            System.out.println("已取消退票操作。");
        }
    }

    private static String getUserRoleName(User.Role role) {
        switch (role) {
            case ADMIN: return "管理员";
            case MANAGER: return "经理";
            case STAFF: return "前台";
            default: return "未知";
        }
    }

    private static int getIntInput() {
        try {
            int input = Integer.parseInt(scanner.nextLine());
            return input;
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    private static double getDoubleInput() {
        try {
            double input = Double.parseDouble(scanner.nextLine());
            return input;
        } catch (NumberFormatException e) {
            return -1;
        }
    }
}
